package br.edu.unibratec.viagemfacil;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBar.TabListener;
import android.support.v7.app.ActionBarActivity;

public class MainActivity extends ActionBarActivity 
	implements TabListener, ClicouNaCategoria, FrasesNosFavoritos {

	ListaCategoriaFragment categorias;
	ListaFavoritosFragment favoritos;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		categorias = (ListaCategoriaFragment) getSupportFragmentManager().
					findFragmentByTag("f1");
		favoritos = (ListaFavoritosFragment)
				getSupportFragmentManager().
					findFragmentByTag("f2");
		
		if (categorias == null || favoritos == null){
			categorias = new ListaCategoriaFragment();
			favoritos = new ListaFavoritosFragment();
			
			getSupportFragmentManager()
				.beginTransaction()
				.add(R.id.master, categorias, "f1")
				.add(R.id.master, favoritos, "f2")
				.commit();
		}
		
		ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		
		Tab tab1 = actionBar.newTab();
		tab1.setText("Categorias");
		tab1.setTabListener(this);

		Tab tab2 = actionBar.newTab();
		tab2.setText("Favoritos");
		tab2.setTabListener(this);
		
		actionBar.addTab(tab1);
		actionBar.addTab(tab2);
	}
	
	@Override
	public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
		
	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		if (tab.getPosition() == 0){
			ft.show(categorias).hide(favoritos);
		} else {
			ft.show(favoritos).hide(categorias);
		}
	}

	@Override
	public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
		
	}

	private boolean isTablet(){
		return findViewById(R.id.detail) != null;
	}

	@Override
	public void categoriaFoiClicada(Frase frase) {
		if (isTablet()){
			DetalheFragment d = DetalheFragment.novaInstancia(post);
			
			getSupportFragmentManager()
				.beginTransaction()
				.replace(R.id.detail, d)
				.commit();			
		} else {
			Intent it = new Intent(this, DetalheActivity.class);
			it.putExtra("post", post);
			startActivity(it);
		}		
	}

	@Override
	public void fraseAdicionadoAosFavoritos(Frase frase) {
		favoritos.refreshList();
		
	}
}